import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class ReportController extends GetxController {
  final reasons = ["政治敏感", "色情敏感", "涉及赌博", "血腥暴恐", "欺诈骗钱", "持续谩骂"];

  var selectedReasonIndex = -1;

  List<ReportImageModel> selectedImages = [];

  static const int _maxCount = 9;

  @override
  void onInit() {
    super.onInit();

    var imageModel = ReportImageModel(0, null, true);
    selectedImages.add(imageModel);
  }

  updateReasonIndex(int index) {
    selectedReasonIndex = index;
    update();
  }

  pickerImages() async {
    final count = selectedImages.where((x) => x.isAddBtn == false).length;
    int limitCount = _maxCount - count;

    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      Get.context!,
      pickerConfig: AssetPickerConfig(
        maxAssets: limitCount,
        requestType: RequestType.image,
        specialPickerType: SpecialPickerType.noPreview,
        textDelegate: const AssetPickerTextDelegate(),
      ),
    );
    if (result != null) {
      final assets = result.toList();

      for (var i = 0; i < assets.length; i++) {
        var imageModel = ReportImageModel(i, assets[i], false);
        selectedImages.add(imageModel);
      }
      selectedImages.sort((a, b) => a.isAddBtn == true ? 1 : -1);
      _checkAddBtn();
      update();
    }
  }

  _checkAddBtn() {
    if (selectedImages.length > _maxCount) {
      selectedImages.removeWhere((x) => x.isAddBtn == true);
    } else {
      var c = selectedImages.where((x) => x.isAddBtn).length;
      if (c == 0) {
        var imageModel = ReportImageModel(0, null, true);
        selectedImages.add(imageModel);
      }
    }
  }

  void removeImage(int index) {
    selectedImages.removeAt(index);
    _checkAddBtn();
    update();
  }
}

class ReportImageModel {
  int index;
  AssetEntity? asset;
  bool isAddBtn;

  ReportImageModel(this.index, this.asset, this.isAddBtn);
}
